<template>
  <div class="order-apply-invoice">
    <div id="stackedMain" style="width: 100%; height: 400px;"></div>
  </div>
</template>
<script lang="ts" setup>
import {onMounted, watch,nextTick,onBeforeUnmount} from 'vue'
import * as echarts from 'echarts'
const emits = defineEmits(['packedBoxQuantity','returnBoxQuantity'])
const props = defineProps({
config: {
    type: Object,
    default: () => ({}),
  },
})

// 保存图表实例
let chartInstance: echarts.ECharts | null = null
const initChart = ()=> {
  const chartDom = document.getElementById('stackedMain')
  if (!chartDom) return
   // 销毁旧实例（如果存在）
  // if (chartInstance) {
  //   chartInstance.dispose()
  // }
  // 初始化新实例
  if(!chartInstance){
    chartInstance = echarts.init(chartDom)
     // 添加点击事件监听（关键修改）
    chartInstance.on('click', (params) => {
      if (params.seriesName == '已提回调箱量') {
        emits("packedBoxQuantity",params)
      } else if (params.seriesName == '已还回调箱量') {
        emits("returnBoxQuantity",params)
      }
    })
  }
  
  let option = {
    legend: {
      right: '50px',
      top: '30px',
      data: ['已提回调箱量', '已还回调箱量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Array.from(props.config.xAxisData || [])
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '已提回调箱量',
        stack: 'Total',
        data: Array.from(props.config.packedBoxQuantity || []),
        type: 'line',
        label: {
            show: true, // 显示标签
            position: 'top',
            formatter: '{c}个', // 显示数据值
          }
      },
      {
        name: '已还回调箱量',
        stack: 'Total',
        data: Array.from(props.config.returnBoxQuantity || []),
        type: 'line',
        label: {
            show: true, // 显示标签
            position: 'top',
            formatter: '{c}个', // 显示数据值
          }
      }
    ]
  };
  chartInstance.setOption(option)
 
  // nextTick(() => { 
  //   echarts.init(document.getElementById('stackedMain')).setOption(option);
  // })
}

watch(() => props.config,(newVal) =>{
  if(newVal){
    console.log("11111",props.config)
    console.log("22222",props.lineChartInfo)
    initChart()
  }
},{deep: true})
onMounted(() => { 
  nextTick(() => {
    initChart()
  })
})  
onBeforeUnmount(() => {
  // 组件卸载时销毁图表
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>
<style lang="scss" scoped></style>